package br.com.puc.models.interceptors;

import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.puc.controllers.UsuarioController;
import br.com.puc.models.SessaoUsuario;
import br.com.puc.models.annotations.Publico;

@Intercepts
public class LoginInterceptor implements Interceptor {

    private Result result;
    private SessaoUsuario sessaoUsuario;

    public LoginInterceptor(Result result, SessaoUsuario userSession) {
        this.result = result;
        this.sessaoUsuario = userSession;
    }

    public boolean accepts(ResourceMethod method) {
        return 
            !(method.getMethod().isAnnotationPresent(Publico.class) ||
            method.getResource().getType().isAnnotationPresent(Publico.class));
    }

    public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) {
        if (sessaoUsuario.isLogado()) {
            stack.next(method, resourceInstance);
        } else {
            result.redirectTo(UsuarioController.class).login();
        }
    }

}
